package com.hema.auction.widget.view;

import android.content.Context;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.hema.auction.R;
import com.hema.auction.base.BaseLayout;
import com.hema.auction.bean.GoodsInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.GlideUtils;
import com.hema.auction.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * author by john
 */

public class HotAuctionView extends BaseLayout {

    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.iv_price_bg)
    ImageView ivPriceBg;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.iv_deal)
    ImageView ivDeal;
    @BindView(R.id.iv_collection)
    ImageView ivCollection;
    @BindView(R.id.tv_auction)
    TextView tvAuction;
    @BindView(R.id.tv_ten_zone)
    ImageView tvTenZone;
    private GoodsInfo info;
    private int postDelayedTime = 1000, postDelayedHttp = 2000, status, countDownTime;
    private String goodsId;
    private Call call;

    public HotAuctionView(Context context) {
        super(context);
        init();
    }

    public HotAuctionView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HotAuctionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        ButterKnife.bind(this, LayoutInflater.from(getContext()).inflate(R.layout.layout_goods_view, this));
    }

    public void setInfo(GoodsInfo info) {
        this.info = info;
        countDownTime = info.getCountdown();
        setData();
    }

    public void setData() {
        ivPriceBg.setVisibility(GONE);
        goodsId = info.getId();
        tvTime.setText(Utils.countDown(countDownTime));
        tvPrice.setText(Utils.priceUnitFormat(getContext(), info.getNowPrice()));
        tvName.setText(info.getOwnerName());
        GlideUtils.load(getContext(), info.getImg(), ivImg);
        if (info.getIsCollected() == 1) {
            ivCollection.setImageResource(R.drawable.ic_collection_sel);
        } else {
            ivCollection.setImageResource(R.drawable.ic_collection_def);
        }
//        if (info.isTenZone()) {
//            tvTenZone.setVisibility(VISIBLE);
//        } else {
            tvTenZone.setVisibility(GONE);
//        }
        getDefaultHandler().removeCallbacks(countDownRun);
//        cancelCall();
        getDefaultHandler().removeCallbacks(refreshGoodsRun);
        if (info.getIsOnSale() == 1) {
            /**
             * 竞拍中
             */
            getDefaultHandler().postDelayed(countDownRun, postDelayedTime);
//            getDefaultHandler().postDelayed(refreshGoodsRun, postDelayedHttp);
            getDefaultHandler().post(refreshGoodsRun);
            setAnima();
            tvAuction.setText("参与竞拍");
            tvAuction.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            ivDeal.setVisibility(GONE);
        } else {
            /**
             * 竞拍结束
             */
            tvAuction.setBackgroundColor(getResources().getColor(R.color.gray99));
            tvAuction.setText("竞拍结束");
            tvTime.setText(Utils.countDown(0));
            ivDeal.setVisibility(VISIBLE);
        }
    }

    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == VISIBLE) {
            if (info != null) {
                refresgGoods();
                setData();
            }
        } else {
            getDefaultHandler().removeCallbacks(countDownRun);
            cancelCall();
            getDefaultHandler().removeCallbacks(refreshGoodsRun);
        }
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
    }

    /**
     * 刷新当前商品竞拍状态
     */
    private void refresgGoods() {
        if (!Utils.isEmpty(goodsId))
            call = HttpManager.getInstance(getContext()).getGoodOrder(goodsId, this);
    }

    private Runnable countDownRun = new Runnable() {
        @Override
        public void run() {
            getDefaultHandler().sendEmptyMessage(100);
        }
    };

    private Runnable refreshGoodsRun = new Runnable() {
        @Override
        public void run() {
            refresgGoods();
        }
    };

    private void setAnima() {
        ivPriceBg.setVisibility(VISIBLE);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0f);
        alphaAnimation.setDuration(1000);
        alphaAnimation.setFillAfter(true);
        ivPriceBg.startAnimation(alphaAnimation);
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_GOOD_ORDER:
                try {
                    if (result.getInt("errcode") == 0) {
                        JSONArray jsonArray = result.getJSONArray("data");
                        if (jsonArray.length() > 0) {
                            JSONObject data = jsonArray.getJSONObject(0);
                            status = data.getInt("status");//状态，1竞拍中，2结束竞拍
                            info.setIsOnSale(status);
                            info.setOwnerName(data.getString("owner_name"));
                            float nowPrice = Float.valueOf(data.getString("now_price"));
                            if (status == 1) {
                                ivDeal.setVisibility(GONE);
                                if (nowPrice > 0) {
                                    if (info.getNowPrice() != nowPrice) {
                                        countDownTime = info.getTolBuytime();
                                        setAnima();
                                        getDefaultHandler().removeCallbacks(countDownRun);
                                        getDefaultHandler().postDelayed(countDownRun, postDelayedTime);
                                    }
                                    tvName.setText(data.getString("owner_name"));
                                    tvTime.setText(Utils.countDown(countDownTime));
                                }
                                tvAuction.setText("参与竞拍");
                                tvAuction.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                            } else {
                                tvName.setText(data.getString("owner_name"));

                                tvTime.setText(Utils.countDown(0));
                                ivDeal.setVisibility(VISIBLE);
                                tvAuction.setBackgroundColor(getResources().getColor(R.color.gray99));
                                tvAuction.setText("竞拍结束");
                            }
                            tvPrice.setText(Utils.priceUnitFormat(getContext(), nowPrice));
                            info.setNowPrice(nowPrice);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        getDefaultHandler().removeCallbacks(refreshGoodsRun);
        if (status == 1) {
            getDefaultHandler().postDelayed(refreshGoodsRun, postDelayedHttp);
        }
    }

    private void cancelCall() {
        if (call != null)
            call.cancel();
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case 100:
                if (status == 1) {
                    if (countDownTime > 1) {
                        countDownTime--;
                        tvTime.setText(Utils.countDown(countDownTime));
                        getDefaultHandler().removeCallbacks(countDownRun);
                        getDefaultHandler().postDelayed(countDownRun, postDelayedTime);
                    }
                } else {
                    tvTime.setText(Utils.countDown(0));
                }
                break;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getDefaultHandler().removeCallbacks(countDownRun);
        cancelCall();
        getDefaultHandler().removeCallbacks(refreshGoodsRun);
    }
}
